<template>
  <div class="warehouseEdit">
    <div class="left">
      <el-form :model="warehouseFrom" :rules="rules" ref="warehouseFrom">
        <el-form-item label="城市:" :label-width="formLabelWidth" prop="cityId">
          <el-select
            v-model="warehouseFrom.cityId"
            size="small"
            style="width: 180px;"
            placeholder="请选择城市"
            @change="getcityIdslist"
          >
            <el-option
              v-for="item in cityList"
              :key="item.id"
              size="small"
              :label="item.deptName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称:" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model.trim="warehouseFrom.name"
            size="small"
            autocomplete="off"
            onafterpaste="value=value.replace(/^[\u0391-\uFFE5A-Za-z]+$/,'').slice(0,20)"
            maxlength="20"
            style="width: 180px;"
          ></el-input>
        </el-form-item>

        <el-form-item label="仓库类型:" :label-width="formLabelWidth" prop="type">
          <el-select
            v-model="warehouseFrom.type"
            size="small"
            style="width: 180px;"
            placeholder="请选择仓库类型"
            @change="getwarehousetypeId"
          >
            <el-option
              v-for="item in warehousetypeList"
              :key="item.id"
              size="small"
              :label="item.dictValue"
              :value="item.dictKey"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="区域:" :label-width="formLabelWidth" prop="deptName" >
          <el-select
            v-model="warehouseFrom.deptId"
            size="small"
            style="width: 180px;"
            placeholder="请选择区域"
            @visible-change="getareadataList"
          >
            <el-option
              v-for="item in areadataList"
              :key="item.id"
              size="small"
              :label="item.deptName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="中央厨房:" :label-width="formLabelWidth" class='removeAfter'>
          <el-select
            v-model="warehouseFrom.kitchenName"
            size="small"
            style="width: 180px;"
            placeholder="请选择中央厨房"
            @change="changeNewPrice($event, 'kitchenName')"
            clearable
          >
            <el-option
              v-for="item in centralKitchen"
              :key="item.id"
              size="small"
              :label="item.name"
              :value="{name:item.name,id:item.id,select:'kitchenName'}"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="生产站:" :label-width="formLabelWidth" class='removeAfter'>
          <el-select
            v-model="warehouseFrom.productionName"
            size="small"
            style="width: 180px;"
            placeholder="请选择生产总仓"
            @change="changeNewPrice($event, 'productionName')"
            clearable
          >
            <el-option
              v-for="item in transfer"
              :key="item.id"
              size="small"
              :label="item.name"
              :value="{name:item.name,id:item.id,select:'productionName'}"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="中转仓:" :label-width="formLabelWidth" class='removeAfter'>
          <el-select
            v-model="warehouseFrom.transferName"
            size="small"
            style="width: 180px;"
            placeholder="请选择中转仓"
            @change="changeNewPrice($event, 'transferName')"
            clearable
          >
            <el-option
              v-for="item in production"
              :key="item.id"
              size="small"
              :label="item.name"
              :value="{name:item.name,id:item.id,select:'transferName'}"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="仓库地址:" :label-width="formLabelWidth" prop="address">
          <div style="position:relative;">
            <el-input
              id="getDetail"
              v-model.trim="warehouseFrom.address"
              size="small"
              autocomplete="off"
              style="width: 180px;"
              @input.native="SearchAddress"
            ></el-input>
            <div class="adressDetailDiv" v-show="adressDetailDivshow">
              <ul v-if="addressFlag" class="adressDetail">
                <li
                  class="pd-10"
                  v-for="(addressitem,index) in addressList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
                  :key="index"
                  :data-name="addressitem.name"
                  :data-lng="addressitem.location.lng"
                  :data-lat="addressitem.location.lat"
                  @click="getlnglat($event)"
                  @mouseover="changeColor($event)"
                  @mouseout="loseColor($event)"
                >
                  <div class="fz-16 fw-bold">{{ addressitem.name }}</div>
                  <div class="c-999 lh-24">
                    地址：<span>{{ addressitem.address }}</span>
                  </div>
                  <div class="c-999 lh-24">
                    城市：<span>{{ addressitem.district }}</span>
                  </div>
                </li>
              </ul>
              <i class="close el-icon-error Delgoodlist" @click="headleclose" v-if="addressFlag&&addressList&&addressList.length"></i>
              <el-pagination
                v-if="addressFlag"
                background
                :current-page.sync="currentPage"
                layout="prev, pager, next"
                :page-sizes="[5, 10, 15, 20]"
                :page-size.sync="pagesize"
                :total="addressList.length"
                @current-change="handleCurrentChange"
                @size-change="handleSizeChange"
                style="margin-top: 5px"
              ></el-pagination>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="仓库经纬度:" :label-width="formLabelWidth">
          <el-input
            v-model="warehouseFrom.longitude"
            size="small"
            placeholder="经度"
            class="w-100"
          ></el-input>
          <el-input
            v-model="warehouseFrom.latitude"
            size="small"
            class="w-100 ml-10"
            placeholder="维度"
          ></el-input>
        </el-form-item>
        <el-form-item label="配送时间:" :label-width="formLabelWidth">
          <el-tag v-for="(time, index) in warehouseFrom.deliveryTimes" style="margin-right: 10px" type="success">
            {{time.deliveryStartTime.substr(0, 5)}}-{{time.deliveryEndTime.substr(0, 5)}},{{time.orderAdvanceTime}}分钟</el-tag>
          <el-button size="small" type="primary" @click="editTimesDialogVisible=true" plain>修改配置</el-button>

        </el-form-item>
        <el-form-item label="销售组织ID:" :label-width="formLabelWidth" prop="salesOrganizationId">
          <el-input
            v-model.trim="warehouseFrom.salesOrganizationId"
            size="small"
            type="textarea"
            maxlength="64"
            show-word-limit
            autocomplete="off"
            style="width: 180px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="销售组织名称:" :label-width="formLabelWidth" prop="salesOrganizationName">
          <el-input
            v-model.trim="warehouseFrom.salesOrganizationName"
            size="small"
            autocomplete="off"
            style="width: 180px;"
            type="textarea"
            maxlength="64"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="是否中转超时提醒:" :label-width="formLabelWidth" prop="transferPrompt">
          <el-switch v-model="warehouseFrom.transferPrompt" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <div class="bd-t">
          <productLabel ref="productLabel"></productLabel>
        </div>
        <div class="bd-t">
          <h4>蛋糕生产站信息</h4>
          <el-form-item :required="false" label="地址:" :label-width="formLabelWidth" prop="pickAddress">
            <el-input
              v-model.trim="warehouseFrom.pickAddress"
              size="small"
              autocomplete="off"
              style="width: 180px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="经度:" :label-width="formLabelWidth" prop="pickLongitude">
            <el-input
              v-model.trim="warehouseFrom.pickLongitude"
              size="small"
              autocomplete="off"
              style="width: 180px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="纬度:" :label-width="formLabelWidth" prop="pickLatitude">
            <el-input
              v-model.trim="warehouseFrom.pickLatitude"
              size="small"
              autocomplete="off"
              style="width: 180px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人:" :label-width="formLabelWidth" prop="storeContact">
            <el-input
              v-model.trim="warehouseFrom.storeContact"
              size="small"
              autocomplete="off"
              style="width: 180px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话:" :label-width="formLabelWidth" prop="storeMobile">
            <el-input
              v-model.trim="warehouseFrom.storeMobile"
              size="small"
              autocomplete="off"
              style="width: 180px;"
            ></el-input>
          </el-form-item>
        </div>
        <div class="tipsbutton">
          <el-button
            type="primary"
            plain
            size="small"
            @click="Selectwarehouse(warehouseFrom)"
            v-if="warehouseFrom.type!=3"
          >编辑仓库范围</el-button>
          <!-- <el-button type="primary" plain size="small" @click="OverFence">结束编辑仓库范围</el-button> -->
          <!-- <el-row style="text-align: right;padding:10px"> -->
          <el-button
            type="danger"
            plain
            size="small"
            @click="removeFence(warehouseFrom)"
            v-if="warehouseFrom.type!=3"
          >删除仓库地图</el-button>
          <!-- </el-row> -->
          <el-button
            type="success"
            size="small"
            @click="handlecommit('warehouseFrom',warehouseFrom)"
          >提交</el-button>
        </div>
      </el-form>
      
    </div>
    <div class="right">
      <div class="amap-page-container">
        <XmMap ref="xmMap" style="width: 100%;height: 700px; margin: 0;" :hasScreenBtn="true"></XmMap>
        <!-- 电子围栏 -->
      </div>
    </div>
    <el-dialog
      :append-to-body="true"
      title="配送时间"
      :visible.sync="editTimesDialogVisible"
      width="50%">
      <div style="margin-bottom: 20px">
        <el-tag @click="openEditDeliveryTime(time)"
                @close="removeDeliveryTime(time,index)"
                v-for="(time, index) in warehouseFrom.deliveryTimes" style="margin-right: 10px" type="success" closable>
          {{time.deliveryStartTime.substr(0, 5)}}-{{time.deliveryEndTime.substr(0, 5)}},{{time.orderAdvanceTime}}分钟</el-tag>
        <el-button type="success" size="small" icon="el-icon-plus" @click="openEditDeliveryTime(null)" circle></el-button>
      </div>

      <div  class="type-button">
        <el-button type="success" size="small" @click="editTimesDialogVisible=false">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :append-to-body="true"
      title="配送时间设置"
      :visible.sync="addTimesDialogVisible"
      width="50%">
      <el-form style="margin-bottom: 20px">
        <el-form-item label="开始配送时间:">
          <el-time-select
            v-model="modalTime.deliveryStartTime"
            :picker-options="{
             start: '08:00',
             step: '00:30',
             end: '24:00'
            }"
            placeholder="选择开始配送时间"
          ></el-time-select>
        </el-form-item>
        <el-form-item label="结束配送时间:">
          <el-time-select
            v-model="modalTime.deliveryEndTime"
            :picker-options="{
             start: '08:00',
             step: '00:30',
             end: '24:00'
           }"
            placeholder="选择结束配送时间"
          ></el-time-select>
          <el-form-item label="下单提前时间:" style="margin-top: 15px">
            <el-input
              v-model="modalTime.orderAdvanceTime"
              size="small"
              min="0"
              style="width: 180px;"
              type="number"
            ></el-input>分钟
          </el-form-item>
        </el-form-item>
      </el-form>

      <div  class="type-button">
        <el-button type="success" size="small" @click="editDeliveryTime">确定</el-button>
      </div>
    </el-dialog>
  </div>

</template>
<script>
import {
  getMainWarehouseList,
  selectDeptByCityId,
  deptdepts,
  warehouseupdate,
  getWarehousePage,
  warehousetype,
  ProductionWarehouseByCity,
  getWarehouseByType,      // 3仓列表
} from "@/api/warehouse";
import productLabel from "./productLabel.vue";
import { inputTipThrottle } from '@/util/map'
export default {
  components: {
    productLabel,
  },
  data: function () {
    return {
      editTimesDialogVisible:false,
      addTimesDialogVisible: false,
      centralKitchen: [],    // 中央厨房
      transfer: [],     //中转仓
      production: [],   //生产厂
      warehouseFrom: {},
      rules: {
        name: [
          {
            required: true,
            message: "仓库名称不能为空",
            trigger: "blur",
          },
          {
            pattern: /^[\u0391-\uFFE5A-Za-z]+$/,
            message: "仓库名称必须包含中英文",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择仓库类型",
            trigger: "blur",
          },
        ],
        cityId: [
          {
            required: true,
            message: "请选择城市",
            trigger: "blur",
          },
        ],
        // parentId: [
        //   {
        //     required: true,
        //     message: "请选择总仓",
        //     trigger: "blur",
        //   },
        // ],
        deliveryStartTime: [
          {
            required: true,
            message: "请选择配送开始时间",
            trigger: "change",
          },
        ],
        deliveryEndTime: [
          {
            required: true,
            message: "请选择配送结束时间",
            trigger: "change",
          },
        ],
        deptId: [
          {
            required: true,
            message: "请选择区域",
            trigger: "blur",
          },
        ],
        // address: [{
        //   required: true,
        //   message: "请输入仓库地址",
        //   trigger: "blur"
        // }],
        orderAdvanceTime: [
          {
            required: true,
            message: "请输入下单提前时间",
            trigger: "blur",
          },
          {
            type: "number",
            pattern: /[^\d]|^[0]/g,
            message: "下单提前时间只能输入数字",
            trigger: "blur",
            max: 6,
          },
        ],
        salesOrganizationId: [
          {
            required: true,
            message: "请输入销售组织ID",
            trigger: "blur",
          },
        ],
        salesOrganizationName: [
          {
            required: true,
            message: "请输入销售组织名称",
            trigger: "blur",
          },
        ],
      },
      formLabelWidth: "160px",
      cityList: [],
      areadataList: [],
      // 地图
      fenceForm: {
        coordinate: [],
      },
      mouseTool: null,
      //仓库地址
      addressFlag: false,
      addressList: [], // 地址详情列表
      pagesize: 5,
      currentPage: 1,
      warehouseData: {
        page: 1,
        size: 10,
      },
      adressDetailDivshow: false, //
      warehousetypeList: [], //仓库类型
      modalTime: { deliveryStartTime: null, deliveryEndTime: null, orderAdvanceTime: null} //配送时间
    };
  },

  mounted() {
    var saberareaName = JSON.parse(localStorage.getItem("saber-areaname"));
    var cityId = JSON.parse(localStorage.getItem("saber-areaId"))["content"];
    this.cityareaName = saberareaName["content"];
    this.getwarehousetype();
    this.getgetWarehouseByType(cityId)    // 获取3仓列表
    this.citydataList()
  },
  methods: {
    // 获取当前上传的数据
    changeNewPrice(data, type){
      // 中央厨房  kitchenId 中转仓  transferId  生产站  productionId
      if(type == "productionName"){
        this.warehouseFrom.productionName = data ? data.name : ''
        this.warehouseFrom.productionId = data ? data.id : ''
      }else if(type == 'kitchenName'){
         this.warehouseFrom.kitchenName = data ? data.name : ''
         this.warehouseFrom.kitchenId = data ? data.id : ''
      }else if(type == 'transferName'){
         this.warehouseFrom.transferName = data ? data.name : ''
         this.warehouseFrom.transferId = data ? data.id : ''
      }
    },
    // 3仓列表
    getgetWarehouseByType(item){
      let obj = {}
      obj['cityId'] = item
      getWarehouseByType({...obj,'type':1}).then(res=>{
        this.centralKitchen = res.data.data   // 中央厨房
      })
      getWarehouseByType({...obj,'type':4}).then(res=>{
        this.transfer = res.data.data     //  中转仓
      })
      getWarehouseByType({...obj,'type':2}).then(res=>{
        this.production = res.data.data   // 生产站
      })
    },
    // 处理数据
    getArea(val) {
      this.warehouseFrom = Object.assign({}, val)
      if(val.kitchenName < 0){
        this.warehouseFrom.kitchenName = ''
      }
      if(val.productionName < 0 ){
        this.warehouseFrom.productionName = ''
      }
      if(val.transferName < 0){
        this.warehouseFrom.transferName = ''
      }
      var isPointInRingList = []; // path(是否在区域内)
      if (val.geoJson.geometry !== "") {
        val.geoJson.geometry.coordinates[0].forEach((item, index) => {
          isPointInRingList.push(item);
        });
      }
      this.fenceForm.coordinate = isPointInRingList;

      this.getareadataList()
      this.$nextTick(() => {
        this.$refs.productLabel.init(this.warehouseFrom)
      })

      setTimeout(() => {
        this.getAreaScopeMethod(isPointInRingList);
      }, 0.2 * 1000);
    },
    getAreaScopeMethod(subCoordinate) {
      this.resetMap()
      this.addMarker()
      this.addPolygon(subCoordinate)
      // 缩放地图到合适的视野级别
      this.$refs.xmMap.map.setFitView([this.polygon]);
    },
    addMarker() {
      this.marker = this.$refs.xmMap.createMarker({
        longitude: this.warehouseFrom.longitude,
        latitude: this.warehouseFrom.latitude,
        label: {
          content: `<div class='info'>${this.warehouseFrom.address}</div>`
        },
      })
      this.$refs.xmMap.map.add(this.marker);
    },
    clearMarker() {
      if (this.marker) {
        this.$refs.xmMap.map.remove(this.marker)
        this.marker = null
      }
    },
    addPolygon(subCoordinate) {
      this.polygon = new AMap.Polygon({
        path: subCoordinate,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: "#1791fc",
        zIndex: 50,
      });
      this.$refs.xmMap.map.add(this.polygon);
    },
    resetMap() {
      if (this.mouseTool) {
        this.mouseTool.close(true);
      }
      this.$refs.xmMap.clearMap()
    },
    headleclose() {
      this.adressDetailDivshow = false;
      this.warehouseFrom.address = "";
    },
    getmap() {},

    //定义仓库地址
    SearchAddress() {
      if (this.warehouseFrom.cityId == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
        this.warehouseFrom.address = "";
        return false;
      } else if (this.warehouseFrom.deptId == "") {
        this.$message({
          showClose: true,
          message: "请选择区域",
          type: "warning",
        });
        this.warehouseFrom.address = "";
        return false;
      } else {
        this.addressFlag = true;
        const cityName = this.getCityName()
        inputTipThrottle({
          city: cityName,
          keyword: this.warehouseFrom.address
        }).then(res => {
          this.addressList = res.sort((a, b) => {
            return a.district.includes(cityName) ? -1 : 0
          })
          if (this.addressList && this.addressList.length > 0) {
            this.adressDetailDivshow = true;
          } else {
            this.$message("搜索无结果请重新输入");
            this.adressDetailDivshow = false;
          }
        })
      }
    },
    getCityName() {
      const selected = this.cityList.find(item => item.id === this.warehouseFrom.cityId)
      return selected ? selected.deptName : ''
    },
    // 点击列表获取经纬度
    getlnglat(e) {
      this.clearMarker()
      this.addressFlag = false;
      let pois = e.currentTarget.dataset;
      this.warehouseFrom.latitude = pois.lat;
      this.warehouseFrom.longitude = pois.lng;
      this.warehouseFrom.address = pois.name;
      this.addMarker()
      // 绑定事件移动地图事件
      this.$refs.xmMap.setZoomAndCenter(13, [pois.lng, pois.lat]);
    },
    changeColor(e) {
      e.currentTarget.style.background = "#F5F7FA";
    },
    // 离开列表颜色改变
    loseColor(e) {
      e.currentTarget.style.background = "#fff";
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange(size) {
      this.pagesize = size;
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },
    citydataList() {
      //获取城市列表数据
      deptdepts("").then((response) => {
        this.cityList = response.data.data;
      });
    },
    getcityIdslist(cityId) {
      //获取城市列表ID
      this.warehouseFrom.name = "";
      this.warehouseFrom.address = "";
      this.warehouseFrom.parentId = "";
      this.warehouseFrom.type = "";
      this.warehouseFrom.deptId = "";
      this.warehouseFrom.parentName = "";
      this.warehouseFrom.deliveryStartTime = "";
      this.warehouseFrom.deliveryEndTime = ""; //配送结束时间
      this.warehouseFrom.orderAdvanceTime = ""; //下单提前时间(分钟)
      this.warehouseFrom.salesOrganizationId = ""; //销售组织ID
      this.warehouseFrom.salesOrganizationName = ""; //销售组织名称
      this.warehouseFrom.kitchenName = ''   // 中央厨房
      this.warehouseFrom.productionName = '' // 生场站
      this.warehouseFrom.transferName = ''  //中转仓
      this.fenceForm.coordinate = [];
      // 获取 3 列表
      this.getgetWarehouseByType(cityId)
      if (this.mouseTool) {
        this.mouseTool.close(true);
      }
    },
    getareadataList() {
      //区域下拉
      if (this.warehouseFrom.cityId == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
      } else {
        selectDeptByCityId({
          cityId: this.warehouseFrom.cityId,
        }).then((res) => {
          this.areadataList = res.data.data;
        });
      }
    },

    handlecommit(warehouseFrom, item) {
      this.$refs[warehouseFrom].validate((valid) => {
        if (valid) {
          if (item.salesOrganizationId == "") {
            this.$message({
              showClose: true,
              message: "销售组织ID不能为空 ",
              type: "warning",
            });
            return false;
          } else if (item.salesOrganizationName == "") {
            this.$message({
              showClose: true,
              message: "销售组织不能为空 ",
              type: "warning",
            });
            return false;
          } else if (item.deliveryTimes.length < 1) {
            this.$message({
              showClose: true,
              message: "请配置配送时间",
              type: "warning",
            });
            return false;
          }
          
          if (item.type == "3") {
            this.$confirm("选择自提仓, 是没有配送范围的,确定保存?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            })
              .then(() => {
                const warehouse = this.getParams(item);
                warehouseupdate(warehouse).then((res) => {
                  this.$message({
                    type: "success",
                    message: "操作成功!",
                  });
                  setTimeout(() => {
                    this.listLoading = false;
                  }, 1.5 * 1000);
                  this.$emit("close");
                  this.$emit("getList", this.warehouseData);
                });
              })
              .catch(() => {
                this.$message({
                  type: "info",
                  message: "已取消",
                });
              });
          } else {
            const warehouse = this.getParams(item);
            warehouseupdate(warehouse).then((res) => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              setTimeout(() => {
                this.listLoading = false;
              }, 1.5 * 1000);
              this.$emit("close");
              this.$emit("getList", this.warehouseData);
            });
          }
        } else {
          this.$message({
            message: "信息未填完整",
            type: "warning",
          });
          return false;
        }
      });
    },
    getParams(item) {
      var deliveryTimes = [];
      for (let i = 0; i < item.deliveryTimes.length; i++) {
        deliveryTimes.push({
          deliveryStartTime: item.deliveryTimes[i].deliveryStartTime.substr(0, 5) + ':00',
          deliveryEndTime: item.deliveryTimes[i].deliveryEndTime.substr(0, 5) + ':00',
          orderAdvanceTime: item.deliveryTimes[i].orderAdvanceTime,
          isAutoReceive: 1
        })
      }
      const productLabelParams = this.$refs.productLabel.getParams()
      const params = {
        kitchenId: item.kitchenId > 0 ?  item.kitchenId : 0,     // 中央厨房
        transferId: item.transferId > 0 ? item.transferId : 0,     // 中转仓
        productionId: item.productionId > 0? item.productionId: 0, // 生产仓
        id: item.id,
        cityId: item.cityId, //城市ID
        deptId: item.deptId, //区域ID
        name: item.name, //仓库名称
        address: item.address, //仓库编辑地址
        parentId: item.type == "1" ? 0 : item.parentId, //默认0
        polygonBy:
          item.type == 3
            ? ""
            : this.fenceForm.coordinate.join(";"),
        status: 1, //默认
        type: item.type, //默认
        longitude: item.longitude, //经度
        latitude: item.latitude, // 纬度
        deliveryTimes: deliveryTimes, //配送时间段
        salesOrganizationId: item.salesOrganizationId,
        salesOrganizationName: item.salesOrganizationName,
        pickAddress: item.pickAddress,
        pickLatitude: item.pickLatitude,
        pickLongitude: item.pickLongitude,
        storeContact: item.storeContact,
        storeMobile: item.storeMobile,
        transferPrompt: item.transferPrompt,
        ...productLabelParams,
      }
      return params
    },
    Selectwarehouse(item) {
      console.log(item, item);
      if (this.warehouseFrom.cityId == "") {
        this.$message({
          showClose: true,
          message: "请选择城市",
          type: "warning",
        });
        this.warehouseFrom.address = "";
        return false;
      } else if (this.warehouseFrom.deptId == "") {
        this.$message({
          showClose: true,
          message: "请选择区域",
          type: "warning",
        });
        this.warehouseFrom.address = "";
        return false;
      } else if (this.warehouseFrom.address == "") {
        this.$message({
          showClose: true,
          message: "请选择仓库地址",
          type: "warning",
        });
        return false;
      } else {
        this.resetMap()
        this.addMarker()
        if (this.fenceForm.coordinate && this.fenceForm.coordinate.length) {
          var polygon = new AMap.Polygon({
            path: this.fenceForm.coordinate.map(item => item),
            strokeColor: "#FF33FF",
            strokeWeight: 6,
            strokeOpacity: 0.2,
            fillOpacity: 0.4,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          this.$refs.xmMap.map.add(polygon);
          
          // 缩放地图到合适的视野级别
          this.$refs.xmMap.map.setFitView([polygon]);
          // 缩放地图到合适的视野级别
          polygon.setMap(this.$refs.xmMap.map); //地图上添加折线
          //构造折线编辑对象，并开启折线的编辑状态
          this.$refs.xmMap.map.plugin(["AMap.PolyEditor"], () => {
            var polyEditor = new AMap.PolyEditor(this.$refs.xmMap.map, polygon);
            polyEditor.on('adjust',(e) => {
              this.fenceForm.coordinate = e.target.getPath().map(item => {
                return [item.getLng(), item.getLat()]
              })
            })
            polyEditor.open();
          });
        } else {
          if (this.mouseTool) {
            this.$refs.xmMap.openDrawPolygon()
          } else {
            this.$refs.xmMap.mouseToolPlugin().then(mouseTool => {
              this.mouseTool = mouseTool
              this.$refs.xmMap.openDrawPolygon()
              AMap.event.addListener(mouseTool, "draw", (e) => {
                let path = e.obj.getPath();
                path.forEach((e) => {
                  this.fenceForm.coordinate = path.map(item => {
                    return [item.getLng(), item.getLat()]
                  });
                });
              });
            })
          }
        }
      }
    },
    removeFence(item) {
      this.$confirm("确定删除该仓库的地图范围？ 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.fenceForm.coordinate = [];
          this.resetMap()
          this.addMarker()
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //仓库类型
    getwarehousetype() {
      warehousetype("").then((response) => {
        this.warehousetypeList = response.data.data;
      });
    },
    getwarehousetypeId(data) {
      console.log(this.warehouseFrom.type,'编辑')
      this.warehouseFrom.type = data;
      this.warehouseFrom.parentId = "";
      this.warehouseFrom.deptId = "";
      this.warehouseFrom.parentName = "";
      if (data == "1") {
        this.warehouseFrom.parentId == "";
        // this.getArea(this.warehouseFrom);
      } else if (data == "3") {
        this.fenceForm.coordinate = [];
        if (this.mouseTool) {
          this.mouseTool.close(true);
        }
      } else if (data == "2") {
        // this.getArea(this.warehouseFrom);
      }
    },

    getWarehouseIds(data) {
      this.warehouseFrom.parentId = data.id;
      selectDeptByCityId({
        cityId: this.warehouseFrom.cityId,
      }).then((res) => {
        this.areadataList = res.data.data;
        this.areadataList.forEach((item) => {
          if (data.value == item.id) {
            this.warehouseFrom.deptId = item.id;
          }
        });
      });
    },
    //修改/添加配送时间
    openEditDeliveryTime(time) {
      if(time == null) {
        this.modalTime = { deliveryStartTime: null, deliveryEndTime: null, orderAdvanceTime: 180} //配送时间
        this.modalTime.add = true;
      } else {
        this.modalTime = time;
        this.modalTime.add = false;
      }
      this.addTimesDialogVisible = true;
    },
    editDeliveryTime() {
      if(this.modalTime.add) {
         this.warehouseFrom.deliveryTimes.push(this.modalTime);
      }
      this.addTimesDialogVisible  = false;
    },
    removeDeliveryTime(item, index) {
      this.warehouseFrom.deliveryTimes.splice(index, 1);
    }

  }
};
</script>

<style lang="scss" scoped>
.removeAfter{
  .el-form-item__label::before{
    content: ' ' !important;
  }
}
.el-select-dropdown__item.selected{
  font-weight: normal;
  color: #606266;
}
.warehouseEdit {
  display: flex;
  justify-content: space-between;

  .left {
    width: 35%;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    border: 1px solid #ebeef5;
    background-color: #fff;
    overflow: hidden;
    color: #606266;
    transition: 0.3s;
    margin-bottom: 10px;
    position: relative;
    max-height: 660px;
    overflow: auto;
    .adressDetailDiv {
      background: #fff;
      position: absolute;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      border-radius: 4px;
      z-index: 99;
      box-sizing: border-box;
      width: 350px;

      .adressDetail {
        margin: 0;
        padding: 0;
        list-style: none;
        border: 1px solid #dcdfe6;
        margin-bottom: 5px;
        max-height: 240px;
        overflow: auto;

        li {
          border-bottom: 1px solid #dcdfe6;

          p {
            margin: 0;
            padding: 0 10px;
            list-style: none;
            width: 280px;
            text-align: left;
            line-height: 1.6;

            &:first-child {
              font-size: 17px;
            }

            &:last-child {
              color: #999;
            }
          }
        }
      }

      .close {
        position: absolute;
        right: 24px;
        top: 6px;
        font-size: 16px;
      }
    }
    .el-form-item {
      margin-bottom: 22px !important;
    }

    .tipsbutton {
      text-align: right;
    }
  }

  .right {
    width: 60%;

    .amap {
      width: 100%;
      height: 640px;
    }

    .amap-demo {
      width: 100%;
      height: 700px;
    }
  }

  .bd-t {
    border-top: 1px solid #ddd;
  }
}
</style>
